<style scoped lang="scss">
@import url('index.scss');
</style>

<template>
  <div class="app-container">

    <!--新模版样式-->
    <div class="topsearch">
      <el-row>
        <el-col :span="22" class="searchcol">
          <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="申请人" prop="planUser">
              <el-input v-model="queryParams.planUser" placeholder="请输入申请人" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="申请日期" prop="planDate">
              <el-date-picker clearable v-model="queryParams.planDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择申请日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="预约药品" prop="drugId">
              <el-input v-model="queryParams.drugId" placeholder="请输入预约药品" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <!-- <el-form-item label="申请数量" prop="drugNum">
        <el-input
          v-model="queryParams.drugNum"
          placeholder="请输入申请数量"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
            <!-- <el-form-item label="申请总活度" prop="drugVolMbq">
        <el-input
          v-model="queryParams.drugVolMbq"
          placeholder="请输入申请总活度"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item> -->
            <el-form-item label="使用时间" prop="usageDate">
              <el-date-picker clearable v-model="queryParams.usageDate" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择预约使用时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="使用人员" prop="usagePatine">
              <el-input v-model="queryParams.usagePatine" placeholder="请输入预约使用人员" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="审核人" prop="auditUser">
              <el-input v-model="queryParams.auditUser" placeholder="请输入审核人" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item>
              <el-button class="newButton" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="22" class="rightcol">
          <div class="newbtn" @click="handleAdd" v-hasPermi="['system:durguseplan:add']">
            <img src="@/assets/images/add.svg" alt="">
            <span>新建</span>
          </div>
          <div class="newbtn" v-if="single == false" @click="handleUpdate" v-hasPermi="['system:durguseplan:edit']">
            <img src="@/assets/images/edit.svg" alt=""></img>
            <span>编辑</span>
          </div>
          <div class="newbtn" v-if="multiple == false" @click="handleDelete" v-hasPermi="['system:durguseplan:remove']">
            <img src="@/assets/images/del.svg" alt=""></img>
            <span>删除</span>
          </div>
          <div class="newbtn" @click="handleExport" v-hasPermi="['system:durguseplan:export']">
            <img src="@/assets/images/export.svg" alt=""></img>
            <span>导出</span>
          </div>
          <div class="newbtn" @click="getList">
            <img src="@/assets/images/refresh.svg" alt=""></img>
            <span>刷新</span>
          </div>
        </el-col>
      </el-row>
    </div>




    <!-- <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:durguseplan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:durguseplan:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:durguseplan:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:durguseplan:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row> -->

    <el-table v-loading="loading" :data="durguseplanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="pid" />
      <el-table-column label="申请人" align="center" prop="planUser" />
      <el-table-column label="申请日期" align="center" prop="planDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.planDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约药品" align="center" prop="drugId">
        <template #default="scope">
          <!-- {{ drugdictList }} -->
          <!-- {{ scope.row }} -->
          {{ drugdictList.find(item => item.drugid == scope.row.drugId)?.drugName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="申请数量" align="center" prop="drugNum" />
      <el-table-column label="个体剂量(MBq)" align="center" prop="drugVolMbq" />
      <el-table-column label="药品采购类型" align="center" prop="drugBuytype">
        <template #default="scope">
          {{ ha_drugprocurement_type.find(item => item.value == scope.row.drugBuytype)?.label || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="预约使用时间" align="center" prop="usageDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.usageDate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="预约使用人员" align="center" prop="usagePatine">
        <template #default="scope">
          <!-- {{ scope.row.usagePatine || '-' }} -->
          <!-- {{ patientList }} -->
          {{ patientList.find(item => item.aid == scope.row.usagePatine)?.uname || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="申请状态" align="center" prop="status">
        <template #default="scope">
          <!-- {{ ha_drugapply_status.find(item => item.value == scope.row.status)?.label || '-' }} -->
          <span :class="scope.row.status == 2 ? 'text-success' : 'text-primary'" v-if="scope.row.status == 2">已审核</span>
          <span :class="scope.row.status == 3 ? 'text-danger' : 'text-primary'" v-else-if="scope.row.status == 3">已拒绝</span>
          <span :class="scope.row.status == 1 ? 'text-primary' : 'text-primary'" v-else>待审核</span>
        </template>
      </el-table-column>
      <el-table-column label="审核人" align="center" prop="auditUser" />
      <el-table-column label="审核时间" align="center" prop="auditTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审核备注" align="center" prop="auditRemark" />
      <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['system:durguseplan:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['system:durguseplan:remove']">删除</el-button>
          <el-button link class="newButton" icon="Check" @click="handleShen(scope.row)"
            v-hasPermi="['system:durguseplan:remove']">审核</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改使用申请对话框 -->
    <el-dialog :title="title" v-model="open" width="50%" class="newDialog">
      <el-form ref="durguseplanRef" :model="form" :rules="rules" label-width="140px">
        <div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="申请人" prop="planUser">
                <el-input v-model="form.planUser" placeholder="请输入申请人" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请日期" prop="planDate">
                <el-date-picker clearable v-model="form.planDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择申请日期" disabled>
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="预约药品" prop="drugId">
                <!-- <el-input v-model="form.drugId" placeholder="请输入预约药品" /> -->
                <el-select v-model="form.drugId" placeholder="请选择预约药品" clearable :disabled="mode=='shenhe'">
                  <el-option v-for="item in drugdictList" :key="item.drugid" :label="item.drugName"
                    :value="item.drugid"></el-option>

                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="申请数量" prop="drugNum">
                <el-input v-model="form.drugNum" placeholder="请输入申请数量" :disabled="mode=='shenhe'" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="个体剂量(MBq)" prop="drugVolMbq">
                <el-input v-model="form.drugVolMbq" placeholder="请输入个体剂量(MBq)" :disabled="mode=='shenhe'" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="药品采购类型" prop="drugBuytype">
                <el-select v-model="form.drugBuytype" placeholder="请选择药品采购类型" clearable :disabled="mode=='shenhe'">
                  <el-option v-for="item in ha_drugprocurement_type" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="预约使用人员" prop="usagePatine">
                <!-- <el-input v-model="form.usagePatine" placeholder="请输入预约使用人员" /> -->
                <!-- {{ patientList  }} -->
                <el-select v-model="form.usagePatine" placeholder="请选择预约使用人员" clearable filterable
                  :disabled="mode=='shenhe'" @change="getPatientInfo">
                  <el-option v-for="item in patientList" :key="item.aid" :label="item.uname"
                    :value="item.aid"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预约使用时间" prop="usageDate">
                <!-- <el-date-picker clearable v-model="form.usageDate" type="date" value-format="YYYY-MM-DD"
                  placeholder="请选择预约使用时间">
                </el-date-picker> -->
                <el-date-picker clearable v-model="form.usageDate" type="datetime" format="YYYY-MM-DD HH:mm"
                  :disabled="mode=='shenhe'" value-format="YYYY-MM-DD HH:mm" placeholder="请选择预约使用时间"
                  style="width: 100%;">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="rightInfo" v-if="form.usagePatine">
            <el-col :span="6">
              <span>患者姓名：{{ currentPatient.uname }} </span>
            </el-col>
            <el-col :span="6">
              <span>性别：{{ currentPatient.usex == 1 ? '男' : '女' }}</span>
            </el-col>
            <el-col :span="6">
              <span>身份证号：{{ currentPatient.patientInfo.ucard }}</span>
            </el-col>
            <el-col :span="6">
              <span>手机号：{{ currentPatient.patientInfo.umobile }}</span>
            </el-col>
            <el-col :span="24">
              <span>地址：{{JSON.parse(currentPatient.patientInfo.addresscity).map(item => item).join('') +
                currentPatient.patientInfo.address}}</span>
            </el-col>
            <el-col :span="6">
              <span>预约科室: {{departmentList.find(item => item.kid == currentPatient.kid)?.kname || '-'}}</span>
            </el-col>
            <el-col :span="6">
              <span>预约时间:{{ parseTime(currentPatient.appointmenttime, '{y}-{m}-{d} {h}:{i}') }}</span>
            </el-col>
            <el-col :span="12">
              <!-- {{ currentPatient.appointmentitems }} -->
              <!-- {{ checkList }} -->
              <span>预约检查项目: {{currentPatient.appointmentitems ? JSON.parse(currentPatient.appointmentitems).map(item =>
                checkList.find(listItem => listItem.itemid == item)?.name).join('、') : '-'}}</span>
            </el-col>

            <!-- <el-col :span="6">
              <span>预约状态
                <el-tag v-if="currentPatient.ustatus == 1" type="success">已预约</el-tag>
                <el-tag v-else-if="currentPatient.ustatus == 0" type="danger">未预约</el-tag>
                <el-tag v-else type="info">未知状态</el-tag>
              </span>
            </el-col>
            <el-col :span="6">
              <span>就诊状态:

                <el-tag v-if="currentPatient.pstatus == 1" type="success">已就诊</el-tag>
                <el-tag v-else-if="currentPatient.pstatus == 0" type="danger">未就诊</el-tag>
                <el-tag v-else type="info">未知状态</el-tag>
              </span>
            </el-col> -->
          </el-row>
          <el-row>

          </el-row>
          <el-form-item label="备注" prop="planRemark">
            <el-input v-model="form.planRemark" placeholder="请输入备注" type="textarea" :rows="6"
              :disabled="mode=='shenhe'" />
          </el-form-item>
        </div>
        <div v-if="mode=='shenhe'" class="shenhe">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="审核人" prop="auditUser">
                <el-input v-model="form.auditUser" placeholder="请输入审核人" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="审核时间" prop="auditTime">
                <!-- <el-date-picker clearable v-model="form.auditTime" type="date" value-format="YYYY-MM-DD"
                  placeholder="请选择审核时间">
                </el-date-picker> -->
                <el-date-picker clearable v-model="form.auditTime" type="datetime" value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请选择申请日期" disabled>
                </el-date-picker>

              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="审核备注" prop="auditRemark">
            <el-input v-model="form.auditRemark" placeholder="请输入审核备注" type="textarea" :rows="6" />
          </el-form-item>
          <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审核意见" prop="status">
              <el-radio-group v-model="form.status" @change="handleChange">
                <!-- <el-radio v-for="item in ha_drugapply_status" :key="item.value" :label="item.value">{{ item.label }}</el-radio> -->
                 <el-radio label="2" value="2">通过</el-radio>
                 <el-radio label="3" value="3">拒绝</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">

          </el-col>
        </el-row>
        </div>


      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Durguseplan">
import { listDurguseplan, getDurguseplan, delDurguseplan, addDurguseplan, updateDurguseplan } from "@/api/system/durguseplan"
import { listDrugdict } from "@/api/system/drugdict"  // 获取药品列表
import { listAppiontment  } from "@/api/system/appiontment"
import { listCheckitems } from "@/api/system/checkitems"
import { listDepartment } from "@/api/system/department"

import useUserStore from '@/store/modules/user'
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
const userStore = useUserStore()

const { proxy } = getCurrentInstance()

const { ha_drugprocurement_type } = proxy.useDict('ha_drugprocurement_type') //预约状态
const { ha_drugapply_status } = proxy.useDict('ha_drugapply_status') //预约审核状态

const durguseplanList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")
const mode = ref("addedit") //添加或修改

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    planUser: null,
    planDate: null, //当前时间时分秒
    drugId: null,
    drugNum: null,
    drugVolMbq: null,
    drugBuytype: null,
    usageDate: null,
    usagePatine: null,
    status: null,
    auditUser: null,
    auditTime: null,
    auditRemark: null,
    planRemark: null,
  },
  rules: {
    drugId: [{ required: true, message: '请输入预约药品', trigger: 'blur' }],
    drugNum: [{ required: true, message: '请输入申请数量', trigger: 'blur' }],
    drugVolMbq: [{ required: true, message: '请输入个体剂量(MBq)', trigger: 'blur' }],
    usageDate: [{ required: true, message: '请选择预约使用时间', trigger: 'blur' }],
    usagePatine: [{ required: true, message: '请输入预约使用人员', trigger: 'blur' }],
    planRemark: [{ required: true, message: '请输入备注', trigger: 'blur' }],
  }
})

const { queryParams, form, rules } = toRefs(data)
  // 获取科室列表
const departmentList = ref([])


const drugdictList = ref([])  // 药品列表
const patientList = ref([])  // 预约人员列表
const newParams = ref({
  pageNum: 1,
  pageSize: 1000, //先查询这么多
})
const checkList = ref([])  //检查项


onMounted(async () => {
    //查询所有检查项列表
  const checkitemsResponse = await listCheckitems(newParams.value)
  if (checkitemsResponse.code == 200) {
    checkList.value = checkitemsResponse.rows.map(item => ({
      name: item.itemname,
      itemid: item.itemid,
    })) //名称和itemid形成新数组
    
  } else{
    checkList.value = []
  }
  //获取药品列表数据@鲍小伟20251124
  getDrugdictlist()
  //查询所有已经预约的人员
  getAllAppointUser()
  //列出所有的科室
  getDepartmentList()
  //查询使用申请列表
  getList()
})
// 获取科室列表@鲍小伟20251111
function getDepartmentList() {
  listDepartment(newParams).then(response => {
    console.log(response)
    if(response.code == 200){
      departmentList.value = response.rows
    } else {
      departmentList.value = []
    }
  })
}

//根据预约人员id查询预约人员信息@鲍小伟20251124
const currentPatient = ref({})
function getPatientInfo(){
  if(form.value.usagePatine){
    console.log(form.value.usagePatine)
    let item = patientList.value.find(item => item.aid == form.value.usagePatine)
    if(item){
      // console.log(item)
      currentPatient.value = item
      form.value.usageDate = item.appointmenttime
    }
  }
}
//查询所有已经预约的人员@鲍小伟20251124
function getAllAppointUser(){
  listAppiontment(newParams.value).then(response => {
    console.log(response)
    if(response.total>0){
      patientList.value = response.rows
    }else{
      patientList.value = []
    }
  })
}

//获取药品列表数据@鲍小伟20251124
function getDrugdictlist() {
  listDrugdict(newParams.value).then(response => {
    // console.log(response)
    if(response.total>0){
      drugdictList.value = response.rows
    }else{
      drugdictList.value = []
    }
  })
}

/** 查询使用申请列表 */
function getList() {
  loading.value = true
  listDurguseplan(queryParams.value).then(response => {
    //查询列表
    // console.log(1111)
    // console.log(response)
    durguseplanList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    pid: null,
    planUser: userStore.name, //申请人为当前登录用户
    planDate: dayjs().format('YYYY-MM-DD HH:mm:ss'), //当前时间时分秒,
    drugId: null,
    drugNum: null,
    drugVolMbq: null,
    drugBuytype: null,
    usageDate: null,
    usagePatine: null,
    status: null,
    auditUser: null,
    auditTime: null,
    auditRemark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    planRemark: null,
  }
  proxy.resetForm("durguseplanRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.pid)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
   mode.value = "addedit"
  open.value = true
  title.value = "添加使用申请"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
    mode.value = "addedit"
  const _pid = row.pid || ids.value

  getDurguseplan(_pid).then(response => {
    form.value = response.data
      //添加一下查询患者的信息情况@bao20251124
  getPatientInfo()
    open.value = true
    title.value = "修改使用申请"
  })
}

//审核按钮操作
function handleShen(row){
  reset()
  mode.value = "shenhe"
  const _pid = row.pid || ids.value
  getDurguseplan(_pid).then(response => {
    form.value = response.data
      //添加一下查询患者的信息情况@bao20251124
      form.value.auditTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  getPatientInfo()
    open.value = true
    title.value = "审核使用申请"
  })
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["durguseplanRef"].validate(valid => {
    if (valid) {
      if (form.value.pid != null) {
        updateDurguseplan(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        form.value.status = 1 //待审核
        addDurguseplan(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _pids = row.pid || ids.value
  proxy.$modal.confirm('是否确认删除使用申请编号为"' + _pids + '"的数据项？').then(function() {
    return delDurguseplan(_pids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('system/durguseplan/export', {
    ...queryParams.value
  }, `durguseplan_${new Date().getTime()}.xlsx`)
}

// getList()
</script>
